package org.ly.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

public class RequestUtil {
    public static CustomResponse sendPostRequest(String urlString, Map<String, String> headers, String jsonInputString) {
        CustomResponse response = new CustomResponse();
        try {
            // URL of the API endpoint
            URI uri = new URI(urlString);
            URL url = uri.toURL();
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // Set request method to POST
            connection.setRequestMethod("POST");

            // Set headers
            for (Map.Entry<String, String> header : headers.entrySet()) {
                connection.setRequestProperty(header.getKey(), header.getValue());
            }

            // Allow sending data
            connection.setDoOutput(true);

            // Write JSON data to the request body
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                stringBuilder.append(line.trim());
            }
            in.close();

            String cmdbJson = stringBuilder.toString();
            // Get response code and message
            response.setCode(connection.getResponseCode());
            response.setStatus(connection.getResponseMessage());
            response.setData(cmdbJson);
//            System.out.println(cmdbJson);
        } catch (Exception e) {
            LogUtil.logError(e.toString(), e);
        }
        return response;
    }

}
